package com.isyscore.os.core.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StringDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.math.BigInteger;

import static com.fasterxml.jackson.databind.MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS;

/**
 * @author : zhan9yn
 * @version : 1.0
 * @description : TODO
 * @date : 2022/1/5 2:02 下午
 */
@Component
@RequiredArgsConstructor
public class SerializedConfig implements ApplicationRunner {

    private final ObjectMapper mapper;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        mapper.disable(IGNORE_DUPLICATE_MODULE_REGISTRATIONS);
        mapper.registerModules(blank2NullModule(), long2StringModule());
    }

    private SimpleModule long2StringModule() {
        SimpleModule module = new SimpleModule("Long2StringModule") {
            @Override
            public Object getTypeId() {
                return "long2StringModule";
            }
        };
        module.addSerializer(BigInteger.class, ToStringSerializer.instance);
        module.addSerializer(Long.class, ToStringSerializer.instance);
        return module;
    }

    private SimpleModule blank2NullModule() {
        SimpleModule blank2Null = new SimpleModule("Blank2NullModule") {
            @Override
            public Object getTypeId() {
                return "blank2NullModule";
            }
        };
        blank2Null.addDeserializer(String.class, new StringDeserializer());
        return blank2Null;
    }
}
